package com.easonji.core.util;

import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.easonji.common.constant.dictmap.base.AbstractDictMap;
import com.easonji.common.constant.dictmap.factory.DictFieldWarpperFactory;
import com.easonji.common.util.StringUtils;

/**
 * @ClassName: ContrastUtils
 * @Description: 对比两个对象的变化的工具类
 * @Author: LiuJun
 * @date: 2018/07/12 15:36
 * @Version: 1.0
 * @Copyright: Copyright (c) 2018 - 2019
 */
public class ContrastUtils {

    /**
     * 记录每个修改字段的分隔符
     */
    public static final String SEPARATOR = ";;;";

    /**
     * 比较两个对象pojo1和pojo2,并输出不一致信息
     */
    @SuppressWarnings("rawtypes")
    public static String contrastObj(Class dictClass, String key, Object pojo1, Map<String, String> pojo2)
            throws IllegalAccessException, InstantiationException {
        StringBuilder sb = new StringBuilder();
        AbstractDictMap dictMap = (AbstractDictMap) dictClass.newInstance();
        sb.append(parseMutiKey(dictMap, key, pojo2) + SEPARATOR);
        JSONObject old = (JSONObject) pojo1;
        pojo2.forEach((k, o2) -> {
            String fieldName = dictMap.get(k);
            if (StringUtils.isNotEmpty(fieldName)) {
                Object o1 = StringUtils.valueOf(old.get(k));
                if (!StringUtils.equals(o1, o2)) {
                    String fieldWarpperMethodName = dictMap.getFieldWarpperMethodName(k);
                    if (StringUtils.isNotEmpty(fieldWarpperMethodName)) {
                        Object o1Warpper = DictFieldWarpperFactory.createFieldWarpper(o1, fieldWarpperMethodName);
                        Object o2Warpper = DictFieldWarpperFactory.createFieldWarpper(o2, fieldWarpperMethodName);
                        sb.append("字段名称:" + fieldName + ",旧值:" + o1Warpper + ",新值:" + o2Warpper);
                    } else {
                        sb.append("字段名称:" + fieldName + ",旧值:" + o1 + ",新值:" + o2);
                    }
                    sb.append(SEPARATOR);
                }
            }
        });
        return StringUtils.removeSuffix(sb.toString(), SEPARATOR);
    }

    /**
     * 解析多个key(逗号隔开的)
     *
     * @author liujun
     * @Date 2017/5/16 22:19
     */
    public static String parseMutiKey(AbstractDictMap dictMap, String key, Map<String, String> requests) {
        StringBuilder sb = new StringBuilder();
        String[] keys = key.split(",");
        for (String item : keys) {
            String fieldWarpperMethodName = dictMap.getFieldWarpperMethodName(item);
            String value = requests.get(item);
            if (fieldWarpperMethodName != null) {
                Object valueWarpper = DictFieldWarpperFactory.createFieldWarpper(value, fieldWarpperMethodName);
                sb.append(dictMap.get(item) + "=" + valueWarpper + ",");
            } else {
                sb.append(dictMap.get(item) + "=" + value + ",");
            }
        }
        return StringUtils.removeSuffix(sb.toString(), ",");
    }
}